//
// Created by abc on 2018/7/19.
//

#include "jni.h"
#include "android/log.h"

#define  LOG_TAG    "test===="
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
extern "C" JNIEXPORT
jstring
Java_com_example_abc_jnidemo_MainActivity_getStringToC
        (JNIEnv *env, jobject thiz) {
    char * str = "from c++";
    return env->NewStringUTF(str);
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_abc_jnidemo_MainActivity_getIntToC
        (JNIEnv *env, jobject thiz, jint a, jint b) {

    // TODO
    return a + b;
}
extern "C"
JNIEXPORT jintArray JNICALL
Java_com_example_abc_jnidemo_MainActivity_sort(JNIEnv *env, jobject thiz, jintArray array_) {

    // TODO
    int size = env->GetArrayLength(array_); // 获取数组的长度adb
    int *array = env->GetIntArrayElements(array_, NULL);

    int flay = 0;
    int i ;
    for (i = 0; i < size; ++i) {
        if (*(array + i) > *(array + i + 1)) {
            flay =  *(array + i);
            *(array + i) = *(array + i + 1);
            *(array + i + 1) = flay;
        }

        LOGE("---%d", *(array + i));
    }

    env->ReleaseIntArrayElements(array_, array, 0);

    return array_;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_abc_jnidemo_MainActivity_getArrayLength(JNIEnv *env, jobject instance,
                                                         jintArray array_) {
    jint *array = env->GetIntArrayElements(array_, NULL);

    // TODO
    return env->GetArrayLength(array_);

}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_abc_jnidemo_MainActivity_getArray(JNIEnv *env, jobject instance,
                                                   jintArray array_) {
    jint *array = env->GetIntArrayElements(array_, NULL);

    // TODO
    int size = env->GetArrayLength(array_);
    for (int i = 0; i < size; ++i) {
        *(array + i) +=10;
    }

    env->ReleaseIntArrayElements(array_, array, 0);
}



extern "C"
JNIEXPORT void JNICALL
Java_com_example_abc_jnidemo_MainActivity_fromCToast(JNIEnv *env, jobject instance) {

    // TODO
    jclass clazz = env->FindClass("com/example/abc/jnidemo/MainActivity");
    jmethodID methodId = env->GetMethodID(clazz, "showToast", "(Ljava/lang/String;)V");

    jstring  jstr = env->NewStringUTF("from c Toast");
    env->CallVoidMethod(instance, methodId, jstr);

}